<?php
/**
 * User: ngreduce
 * Date: 07.03.11
 * Time: 19:19
 */
 
class ImportController extends Controller {

    protected $_jobsDb;
    protected $_resumeDb;

    protected $_categories;
    protected $_regions;
    protected $_errStr;

    public function actionIndex()
    {
        $this->_createDbConnection();

        $jobCount = $this->_jobsDb->createCommand('SELECT count(*) from jobs where is_active=1')->queryScalar();
        $resumeCount = $this->_resumeDb->createCommand('SELECT count(*) from jobs where is_active=1')->queryScalar();
        $this->render('index', array('jobCount'=>$jobCount, 'resumeCount'=>$resumeCount));
    }

    public function actionImport()
    {
        set_time_limit(500);
        $this->_errStr = '';

        $this->_createDbConnection();
        $this->_categories = $this->_getSrcCategories();
        $this->_regions = $this->_getSrcRegions();

        $jobCount = $this->_importJobs();
        $resumeCount = $this->_importResume();

        Yii::app()->user->setFlash('import-index', "<h2>Done</h2>\n<ul><li>Errors: {$this->_errStr}</li>\n<li></li>Jobs:{$jobCount}</li></li>Resume:{$resumeCount}</li></ul>");
        $this->redirect($this->createUrl('import/index'));
    }

    protected function _importJobs()
    {
        $limit = 30;
        $offset = 0;

        $count = 0;

        while($jobs = $this->_jobsDb->createCommand()->select('*')->from('jobs')
                ->where('is_active=1')->limit($limit, $offset)->queryAll()) {
            foreach ($jobs as $old_job) {
                $author = User::getUser($old_job['poster_email'], $old_job['company']);
                $job = new Job;
                $job->author_id = ($author != null) ? $author->id : null;
                $this->_importItem($job, $old_job);

                if ($job->save()) {
                    ++$count;
                } else {
                    $this->_errStr .= '<br/>Title: '.$job->title.'<br/>';
                    $this->_errStr .= 'Tags: '.$job->tags.'<br/>';
                    foreach ($job->errors as $field=>$errors) {
                        foreach ($errors as $error) {
                            $this->_errStr .= $error.'<br/>';
                        }
                    }
                }
            }
            $offset += count($jobs);
        }
        return $count;
    }

    protected function _importResume()
    {
        $limit = 30;
        $offset = 0;

        $count = 0;

        while($resume = $this->_jobsDb->createCommand()->select('*')->from('jobs')
                ->where('is_active=1')->limit($limit, $offset)->queryAll()) {
            foreach ($resume as $old_resume) {
                $author = User::getUser($old_resume['poster_email'], $old_resume['company']);
                $model = new Resume;
                $model->author_id = ($author != null) ? $author->id : null;
                $this->_importItem($model, $old_resume);

                if ($model->save()) {
                    ++$count;
                } else {
                    $this->_errStr .= '<br/>Title: '.$model->title.'<br/>';
                    $this->_errStr .= 'Tags: '.$model->tags.'<br/>';
                    foreach ($model->errors as $field=>$errors) {
                        foreach ($errors as $error) {
                            $this->_errStr .= $error.'<br/>';
                        }
                    }
                }
            }
            $offset += count($resume);
        }
        return $count;
    }

    protected function _importItem($model, $sourcedata)
    {
        $model->id = $sourcedata['id'];
        $model->title = $sourcedata['title'];
        $model->content = $sourcedata['description'];
        $model->create_time = strtotime($sourcedata['created_on']);
        $model->update_time = $model->create_time;
        $model->status = Job::STATUS_APPROVED;

        // Tags
        if (isset($this->_categories[$sourcedata['category_id']])) {
            $model->tags .= ',' . $this->_categories[$sourcedata['category_id']];
        }
        if ($sourcedata['city_id'] != -1) {
            if (isset($this->_regions[$sourcedata['city_id']])) {
                $model->tags .= ',' . $this->_regions[$sourcedata['city_id']];
            }
        } elseif (!empty($sourcedata['outside_location'])) {
            $model->tags .= ',' . $sourcedata['outside_location'];
        }

        $model->tags = str_replace('.', ' ', $model->tags); // Workaround for dots in old database
        return $model;
    }

    protected function _getSrcCategories()
    {
        $result = array();
        $raw = $this->_jobsDb->createCommand()->select('*')->from('categories')->queryAll();
        foreach ($raw as $entry) {
            $result[$entry['id']] = $entry['name'];
        }
        return $result;
    }

    protected function _getSrcRegions()
    {
        $result = array();
        $raw = $this->_jobsDb->createCommand()->select('*')->from('cities')->queryAll();
        foreach ($raw as $entry) {
            $result[$entry['id']] = $entry['name'];
        }
        return $result;
    }

    protected function _createDbConnection()
    {
        $this->_jobsDb = new CDbConnection;
        $config = Yii::app()->params['legacyDb']['jobs'];
        foreach($config as $prop=>$value) {
            eval('$this->_jobsDb->'.$prop.'=$value;');
        }
        $this->_jobsDb->setActive(true);

        $this->_resumeDb = new CDbConnection;
        $config = Yii::app()->params['legacyDb']['resume'];
        foreach($config as $prop=>$value) {
            eval('$this->_resumeDb->'.$prop.'=$value;');
        }
        $this->_resumeDb->setActive(true);
    }
}
